console.log('start');
var poll_id = 0;
var base_url = 'http://tmrweb.ikito.ru/polls/ajax';
var poll_data = false;
var vote_key = undefined;

function load_poll_data(poll_id, skip) {
    console.log('load_poll_data');
    url = base_url;
    if (poll_id) {
        url = base_url+"/poll_data/"+poll_id+"/?callback=?";
        if (skip) url += "&skip=true";
    }
    else url = base_url+"/poll_data/?callback=?";
    if (vote_key) url += "&vote_key=" + vote_key;

    console.log('requesting jsonp: '+url);
    $.ajax({
        url: url,
        dataType: 'jsonp',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('load_poll_data error: '+textStatus+'/'+errorThrown);
            poll_data = false;
        },
        success: function(data){
            poll_data = data;
            recieve_poll_data(data);
        }
    });
};
function send_upoll_vote() {
    if (!poll_data || !poll_data.poll) return;
    if (poll_data.poll.answer_type == 'single') {
        var radio = $('#upoll_variants input:radio:checked');
        var poll_id = poll_data.poll.id;
        var vote_data = radio.attr('id')+'=1';
    } else {
        var boxes = $('#upoll_variants input:checkbox:checked');
        var poll_id = poll_data.poll.id;
        var vote_data = '';
        for (i=0; i<boxes.length; i+=1) {
            var box = $(boxes[i]);
            vote_data += box.attr('id')+'=1&';
        };           
    };
    var url = base_url+'/vote/'+poll_id+'/?'+vote_data;
    console.log('voting url: '+url);
    if (poll_id && vote_data) {
        $.ajax({
            url: url,
            dataType: 'jsonp',
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log('send_vote error: '+textStatus+'/'+errorThrown);
            },
            success: function(data){
                recieve_vote_data(data);
            }
        })
    } else {
        console.log('wrong poll_id or name');
    }
};
function recieve_poll_data(data) {
    console.log('recieved: result '+data.result+' action '+data.action);
    if (data.result != 'success' ) show_error_message(data);
    if (data.action == 'vote' ) set_poll_variants(data);
    else if (data.action == 'view_only') show_poll_results(data);
    vote_key = data.vote_key;
};

function recieve_vote_data(data) {
    console.log('recieve_vote_data');
    if (data.result != 'success') show_error_message(data);
    if (data.result == 'success') {
        console.log('successful vote');
        vote_key = data.vote_key;
        load_poll_data(data.poll.id);
    };
}
function show_error_message(data) {
    console.log('error:'+data.explain); 
};
/* 
    принимает массив с данными о голосовании, устанавливает форму голосования в upoll_container
*/
function set_poll_variants(data) {
    console.log('set_poll_variants '+data.poll.title);
    variants = data.variants;
    var html = '<h4>'+data.poll.title+'</h4>';
    html += '<a href=# onclick="load_poll_data(' + data.poll.id +', true); return false">Другой опрос</a>';
    html += '<ul id="upoll_variants" style="list-style: none;  margin-left: 0px; padding-left: 0px;">';
    var input_type = 'radio';
    if (data.poll.answer_type=='multi') input_type = 'checkbox';
    for (i=0; i<variants.length; i+=1) {
        var row = variants[i];
        var row_html = '';
        row_html += '<li><label>';
        row_html += '<input type="'+input_type+'" id="v_'+row.variant_id+'" name="vote_variants" value="1" style="float: left">';
        row_html += row.text;
        row_html += '</label></li>';
        html += row_html;
    };
    html += '</ul>';
    html += '<input type="button" onclick="send_upoll_vote();" value="Отправить">';
    // html += '<p>vote_key='+data.vote_key+'</p>';
    document.getElementById('upoll_container').innerHTML = html;
};
/* 
    принимает массив с данными о голосовании, показывает результаты голосования в upoll_container
*/
function show_poll_results(data) {
    console.log('show_poll_results');
    var html = '<h4>'+data.poll.title+'</h4>';
    html += '<a href=# onclick="load_poll_data(' + data.poll.id +', true); return false">Другой опрос</a>';
    html += '<ul style="list-style: none; margin-left: 0px; padding-left: 0px;">';
    var total_votes = 0;
    for (i=0; i<data.variants.length; i+=1) {
        if (data.variants && data.variants[i]) total_votes += data.variants[i].votes;
    };
    for (i=0; i<data.variants.length; i+=1) {
        var row = data.variants[i];
        var row_html = '';
        row_html += '<li>';
        row_html += row.text+': '+row.votes;
        p = perc(row.votes, total_votes);
        row_html += perc_bar(p);
        row_html += '</li>';
        html += row_html;
    };
    html += '</ul>';
    //html += '<p>vote_key='+data.vote_key+'</p>';
    document.getElementById('upoll_container').innerHTML = html;
};
load_poll_data();
function perc(c, t) {
    if (c == 0) return 0;
    else return Math.round( (c/t)*100 );
};
function perc_bar(p) {
    var result = '<div style="width: 100%; border: 0px; margin-top:-2px; background: #FFEFDB;">';
    result += '<div style="width: '+p+'%; background: '+random_color()+';">'+p+'%</div>';
    result += '</div>';
    return result;
};
function random_color() {
    var colors = [  'PeachPuff', 'MistyRose', 'CornflowerBlue', 'DeepSkyBlue', 'LightSkyBlue', 'LightSteelBlue', 
                    'LightBlue', 'Aquamarine', 'PaleGreen', 'GreenYellow', 'IndianRed', 'Peru', 'Chocolate', 'Firebrick',
                    'Orange', 'DarkOrange', 'HotPink', 'PaleVioletRed', 'MediumOrchid'];
    return colors[Math.floor(Math.random()*colors.length)];
}
